﻿using B.MESUI.Login.BasicData_UI.BasicData;
using B.MESUI.Login.SLY;
using DevExpress.XtraEditors;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace B.MESUI.Login.BasicData_UI
{
    public partial class GetProjectLineForm : DevExpress.XtraEditors.XtraForm
    {
        private int pageIndex = 1;
        private int pageSize = 5; // 可根据需要调整
        private int totalCount = 0;
        private int totalPage = 0;
        // 保存所有车间名称
        private List<string> allWorkshops = new List<string>();
        // 用于保存每行的选中状态
        private Dictionary<int, bool> checkStatus = new Dictionary<int, bool>();
        public GetProjectLineForm()
        {
            InitializeComponent();

            btnFirst.Click += btnFirst_Click;
            btnPrev.Click += btnPrev_Click;
            btnNext.Click += btnNext_Click;
            btnLast.Click += btnLast_Click;
            btnJump.Click += btnJump_Click;
            SearchButton1.Click += SearchButton1_Click;
            ResetsimpleButton2.Click += ResetsimpleButton2_Click;
            this.Load += GetProjectLineForm_Load;

            // 设置ComboBoxEdit支持动态输入和模糊查询
            comboBoxEdit2.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
            comboBoxEdit2.Properties.AutoComplete = false;
            comboBoxEdit2.EditValueChanged += comboBoxEdit2_EditValueChanged;

            // 1. 启用复选框多选
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

            // 2. 添加操作列
            var colAction = new DevExpress.XtraGrid.Columns.GridColumn();
            colAction.Caption = "操作";
            colAction.FieldName = "Action";
            colAction.Visible = true;
            colAction.VisibleIndex = gridView1.Columns.Count;
            gridView1.Columns.Add(colAction);

            var buttonEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            buttonEdit.Buttons.Clear();
            buttonEdit.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph) { Caption = "修改" });
            buttonEdit.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph) { Caption = "删除" });
            buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            colAction.ColumnEdit = buttonEdit;

            // 绑定按钮点击事件
            buttonEdit.ButtonClick += ButtonEdit_ButtonClick;

            //gridView1.CustomRowCellEdit += (s, e) =>
            //{
            //    if (e.Column.FieldName == "Action")
            //        e.RepositoryItem = buttonEdit;
            //};

            gridView1.RowCellClick += async (s, e) =>
            {
                if (e.Column.FieldName == "Action")
                {
                    var row = gridView1.GetRow(e.RowHandle) as GetProjectLineDTO;
                    if (row == null) return;
                    if (e.CellValue != null && e.CellValue.ToString().Contains("修改"))
                    {
                        var editForm = new EditProjectLineForm(row);
                        editForm.EditSuccess += (sender2, args2) => { LoadData(); };
                        editForm.ShowDialog();
                    }
                    else if (e.CellValue != null && e.CellValue.ToString().Contains("删除"))
                    {
                        if (MessageBox.Show("确定要删除该产线吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            await DeleteLine(row.ID);
                            LoadData();
                        }
                    }
                }
            };

            // 3. 批量删除按钮事件
            simpleButton1.Click += async (s, e) =>
            {
                var selectedRows = gridView1.GetSelectedRows();
                List<string> ids = new List<string>();
                foreach (var rowHandle in selectedRows)
                {
                    var row = gridView1.GetRow(rowHandle) as GetProjectLineDTO;
                    if (row != null)
                        ids.Add(row.ID);
                }
                if (ids.Count == 0)
                {
                    MessageBox.Show("请先选择要删除的产线！");
                    return;
                }
                if (MessageBox.Show("确定要批量删除选中的产线吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    using (HttpClient client = new HttpClient())
                    {
                        var url = $"http://39.103.49.30:9982/api/ProjectLine/DeleteListProductionLine?Ids={string.Join(",", ids)}";
                        var response = await client.DeleteAsync(url);
                        if (response.IsSuccessStatusCode)
                        {
                            MessageBox.Show("批量删除成功！");
                            checkStatus.Clear(); // 清空选中状态
                            LoadData();
                        }
                        else
                        {
                            MessageBox.Show("批量删除失败！");
                        }
                    }
                    
                }
            };
        }
        /// <summary>
        /// 下拉
        /// </summary>
        private async void LoadWorkShopList()
        {
            string url = "http://39.103.49.30:9982/api/WorkShop/GetAll"; // 替换为你的实际接口
            using (var client = new System.Net.Http.HttpClient())
            {
                var response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
                    var list = result.resultData;
                    comboBoxEdit2.Properties.Items.Clear();
                    allWorkshops.Clear();
                    foreach (var item in list)
                    {
                        string code = item.id == null ? "" : item.id.ToString();
                        string name = item.workshoP_NAME == null ? "" : item.workshoP_NAME.ToString();
                        string display = $"{code}-{name}";
                        allWorkshops.Add(display);
                        comboBoxEdit2.Properties.Items.Add(display);
                    }
                }
            }
        }
        /// <summary>
        /// 列表分页显示
        /// </summary>
        private async void LoadData()
        {
            //需要查询的字段
            string lineCode = textEdit1.Text.Trim();
            string lineName = textEdit2.Text.Trim();
            string workshopId = comboBoxEdit2.Text.Trim();
            if (!string.IsNullOrEmpty(comboBoxEdit2.Text) && comboBoxEdit2.Text.Contains("-"))
            {
                workshopId = comboBoxEdit2.Text.Split('-')[0];
            }
            //前后端连接 获取后端接口URL
            string url = $"http://39.103.49.30:9982/api/ProjectLine/GetPageProductionLine?PageIndex={pageIndex}&PageSize={pageSize}&LINE_CODE={lineCode}&LINE_NAME={lineName}&WORKSHOP_ID={workshopId}";

            // 根据车间代码和名称构建完整的请求URL
            if (!string.IsNullOrEmpty(lineCode))
                url += $"&LINE_CODE={lineCode}";
            if (!string.IsNullOrEmpty(lineName))
                url += $"&LINE_NAME={lineName}";
            if (!string.IsNullOrEmpty(workshopId))
                url += $"&WORKSHOP_ID={workshopId}";
            // 使用HttpClient发送请求并处理响应
            using (HttpClient client = new HttpClient())
            {
                // 异步获取API响应字符串
                var response = await client.GetStringAsync(url);

                // 解析JSON响应
                JObject obj = JObject.Parse(response);

                // 提取页面数据并转换为List<GetWorkShopDTO>类型
                var datas = obj["pageDatas"];
                var list = datas.ToObject<List<GetProjectLineDTO>>();

                // 将数据源绑定到GridControl并刷新数据源
                gridControl1.DataSource = list;
                gridControl1.RefreshDataSource();

                // 赋值总条数和总页数
                totalCount = obj["totalCount"]?.ToObject<int>() ?? 0;
                totalPage = obj["totalPage"]?.ToObject<int>() ?? 1;


                lblPageInfo.Text = $"当前第 {pageIndex} 页，共 {totalPage} 页，{totalCount} 条记录";
            }
        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            pageIndex = 1;
            LoadData();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                LoadData();
            }
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (pageIndex < totalPage)
            {
                pageIndex++;
                LoadData();
            }
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            pageIndex = totalPage;
            LoadData();
        }

        private void btnJump_Click(object sender, EventArgs e)
        {
            int jumpPage;
            if (int.TryParse(txtJump.Text, out jumpPage) && jumpPage >= 1 && jumpPage <= totalPage)
            {
                pageIndex = jumpPage;
                LoadData();
            }
            else
            {
                MessageBox.Show("请输入有效的页码！");
            }
        }

        private void SearchButton1_Click(object sender, EventArgs e)
        {
            pageIndex = 1;
            LoadData();
        }

        private void ResetsimpleButton2_Click(object sender, EventArgs e)
        {
            textEdit1.Text = "";
            textEdit2.Text = "";
            comboBoxEdit2.Text = "";
            pageIndex = 1;
            LoadData();
        }

        private void GetProjectLineForm_Load(object sender, EventArgs e)
        {
            LoadWorkShopList();
            LoadData();
        }

        private void comboBoxEdit2_EditValueChanged(object sender, EventArgs e)
        {
            // 获取用户在组合框中输入的关键词，并去除前后空格
            string keyword = comboBoxEdit2.Text.Trim();

            // 清空组合框的现有项目，为筛选做准备
            comboBoxEdit2.Properties.Items.Clear();

            // 遍历所有的工作坊名称，寻找匹配的项目
            foreach (var item in allWorkshops)
            {
                // 如果关键词为空或工作坊名称中包含关键词（不区分大小写），则将该工作坊添加到组合框中
                if (string.IsNullOrEmpty(keyword) || item.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    comboBoxEdit2.Properties.Items.Add(item);
                }
            }

            // 显示组合框的弹出窗口，以便用户选择
            comboBoxEdit2.ShowPopup();
         }
        private void AddLinebutton1_Click(object sender, EventArgs e)
        {
            var addForm = new AddProjectLineForm();
            addForm.AddSuccess += (s, args) =>
            {
                LoadData(); // 添加成功后刷新列表
            };
            addForm.ShowDialog();
        }

        // 4. 删除方法
        private async Task DeleteLine(string id)
        {
            using (var client = new HttpClient())
            {
                var response = await client.DeleteAsync($"http://localhost:5198/api/ProjectLine/DeleteProductionLine?Id={id}");
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show("删除成功！");
                    LoadData(); // 删除成功后刷新列表
                }
                else
                {
                    MessageBox.Show("删除失败！");
                }
            }
        }

        // 操作列按钮点击事件
        private async void ButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var row = gridView1.GetFocusedRow() as GetProjectLineDTO;
            if (row == null) return;

            if (e.Button.Caption == "修改")
            {
                // 创建编辑项目行的表单实例
                var editForm = new EditProjectLineForm(row);

                // 注册表单编辑成功事件的处理程序
                editForm.EditSuccess += (sender2, args2) => { LoadData(); };

                // 显示编辑表单对话框
                editForm.ShowDialog();
            }
            else if (e.Button.Caption == "删除")
            {
                if (MessageBox.Show("确定要删除该产线吗？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    await DeleteLine(row.ID);
                    LoadData();
                }
            }
        }


        private void ProjectLineLoadsimpleButton2_Click(object sender, EventArgs e)
        {
            // 调用后端导出接口，假设接口为 /api/WorkShop/Export
            string url = "http://39.103.49.30:9982/api/ProjectLine/Export/export";
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var response =  client.GetAsync(url).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var bytes =  response.Content.ReadAsByteArrayAsync().Result;
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            sfd.Filter = "Excel文件|*.xlsx|所有文件|*.*";
                            sfd.FileName = "产线信息导出.xlsx";
                            if (sfd.ShowDialog() == DialogResult.OK)
                            {
                                System.IO.File.WriteAllBytes(sfd.FileName, bytes);
                                MessageBox.Show("导出成功！");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("导出失败！");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出异常：" + ex.Message);
                }
            }
        }
    }
}